package com.songlanyun.modules.usergains.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.enums.BillConstant;
import com.songlanyun.common.enums.IntegralConstant;
import com.songlanyun.common.enums.UserBillConstant;
import com.songlanyun.common.streamquery.BaseBatchData;
import com.songlanyun.common.streamquery.QueryStreamHandLer;
import com.songlanyun.common.utils.*;
import com.songlanyun.common.utils.custom.MathUtils;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.entity.UserIdentityAssetEntity;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.account.service.UserIdentityAssetService;
import com.songlanyun.modules.advconfig.dao.AdvConfigDao;
import com.songlanyun.modules.advconfig.entity.AdvConfig;
import com.songlanyun.modules.goods.model.vo.GoodsSlimVo;
import com.songlanyun.modules.integralrecord.entity.IntegralRecord;
import com.songlanyun.modules.integralrecord.service.IntegralRecordService;
import com.songlanyun.modules.memberbill.service.SaleRefillCardBillService;
import com.songlanyun.modules.openSwitch.domain.YxtSwitch;
import com.songlanyun.modules.openSwitch.mapper.YxtSwitchMapper;
import com.songlanyun.modules.openSwitch.service.IYxtSwitchService;
import com.songlanyun.modules.pointconfig.entity.PointConfig;
import com.songlanyun.modules.pointconfig.service.PointConfigService;
import com.songlanyun.modules.rabbitmq.MqConstant;
import com.songlanyun.modules.rabbitmq.service.SendMsgService;
import com.songlanyun.modules.usergains.model.UserBillVo;
import com.songlanyun.modules.usergains.service.UserOrderGainsService;
import org.apache.commons.lang.StringUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.songlanyun.modules.usergains.dao.UserBillDao;
import com.songlanyun.modules.usergains.entity.UserBill;
import com.songlanyun.modules.usergains.service.UserBillService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("userBillService")
public class UserBillServiceImpl extends ServiceImpl<UserBillDao, UserBill> implements UserBillService {


    @Resource
    private UserIdentityAssetService userIdentityAssetService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private PointConfigService pointConfigService;

    @Autowired
    private IntegralRecordService integralRecordService;

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Autowired
    private UserOrderGainsService userOrderGainsService;

    @Autowired
    private AdvConfigDao advConfigDao;

    @Autowired
    private YxtSwitchMapper yxtSwitchMapper;

    @Autowired
    private UserBillService userBillService;

    @Autowired
    private SaleRefillCardBillService saleRefillCardBillService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Long userId = MapUtil.getLong(params, "user_id");
        String code = MapUtil.getStr(params, "code");
        Integer billType = MapUtil.getInt(params, "bill_type");

        IPage<UserBill> page = this.page(
                new Query<UserBill>().getPage(params),
                new LambdaQueryWrapper<UserBill>()
                        .eq(userId != null, UserBill::getUserId, userId)
                        .eq(billType != null, UserBill::getBillType, billType)
                        .eq(StringUtils.isNotBlank(code), UserBill::getCode, code)
                        .orderByDesc(UserBill::getCreateTimeMillis)
        );

        return new PageUtils(page);
    }

    @Override
    public List<UserBill> list(Long userId) {
        return this.list(
                new LambdaQueryWrapper<UserBill>()
                        .eq(UserBill::getUserId, userId)
                        .orderByDesc(UserBill::getCreateTimeMillis)
        );
    }

    @Autowired
    private SendMsgService sendMsgService;


    @Override
    public void inBill(Long userId, String remark, UserBillConstant.InnerMode innerMode, BigDecimal entryValue, String code,String operator) {

        UserIdentityAssetEntity userIdentityAssetEntity = userIdentityAssetService.getById(userId);
        if (entryValue.compareTo(userIdentityAssetEntity.getCommissionAble())>0){
            entryValue = userIdentityAssetEntity.getCommissionAble();
        }

        //修改会员可贡献值
        UserIdentityAssetEntity userIdentity = userIdentityAssetService.updateCommissionAble(userId, entryValue, false);

        UserBill userBill = new UserBill();
        userBill.setUserId(userId);
        userBill.setBillType(UserBillConstant.BillType.EXPENDITURE);//出账
        userBill.setOuterMode(UserBillConstant.OuterMode.ORDER_DIVIDENDS);//出账方式
        userBill.setRemark(remark);//备注
        userBill.setCode(code);//单号
        userBill.setEntryBefore(userIdentity.getCommissionAble().add(entryValue));//入帐前的可提现佣金
        userBill.setEntryAfter(userIdentity.getCommissionAble());//入帐后的可提现佣金
        userBill.setEntryValue(entryValue);
        userBill.setOperator(operator);
        this.baseMapper.insert(userBill);

        //修改会员的余额
        saleRefillCardBillService.addBalance(userId,entryValue,code,BillConstant.InnerMode.ORDER_DIVIDENDS,remark);

        if (UserBillConstant.InnerMode.BUY_INCOME.equals(innerMode)) {
            System.out.println("加入mq成功");
            sendMsgService.sendCommon(MqConstant.UserUpgradeConstant.USER_UPGRADE_EXCHANGE, MqConstant.UserUpgradeConstant.USER_UPGRADE_ROUTER
                    , userId.toString());
        }

    }

    @Override
    public void outBill(Long userId, String remark, UserBillConstant.OuterMode outerMode, BigDecimal entryValue, String code,String operator) {
        //修改会员可提现金额
        UserIdentityAssetEntity userIdentity = userIdentityAssetService.updateCommissionAble(userId, entryValue, false);

        UserBill userBill = new UserBill();
        userBill.setUserId(userId);
        userBill.setBillType(UserBillConstant.BillType.EXPENDITURE);//出账
        userBill.setOuterMode(outerMode);//出账方式
        userBill.setRemark(remark);//备注
        userBill.setCode(code);//单号
        userBill.setEntryBefore(userIdentity.getCommissionAble().add(entryValue));//出账前的可提现佣金
        userBill.setEntryAfter(userIdentity.getCommissionAble());//出账后的可提现佣金
        userBill.setEntryValue(entryValue);
        userBill.setOperator(operator);
        this.baseMapper.insert(userBill);
    }


    @Override
    public void batchProcess(Integer batchSize, Consumer<BaseBatchData> consumer) {
        QueryStreamHandLer<AccountEntity> exportResultHandler = new QueryStreamHandLer<>(batchSize);
        exportResultHandler.consumer = consumer;
        sqlSessionTemplate.select("com.songlanyun.modules.account.dao.AccountDao.getAllActivatingUsers", exportResultHandler);
        exportResultHandler.endProcess();
    }


    @Override
    public void batchActivationAndAirdrop(BigDecimal allActivationUseCommissionAble,List<?> data) {
        PointConfig config = pointConfigService.loadConfig(true);
        if(ObjectUtil.isNull(config))
        {
            return;
        }
        //BigDecimal allActivationUseCommissionAble= userIdentityAssetService.countAllActivationUseCommissionAble();
        if(allActivationUseCommissionAble.compareTo(BigDecimal.ZERO)==0)
        {
            return ;
        }

        //广告配置
        AdvConfig advConfig = advConfigDao.selectOne(new LambdaQueryWrapper<AdvConfig>().orderByDesc(AdvConfig::getId).last("LIMIT 1"));
        //每天观看广告次数
        Integer seeTimesOneDay = advConfig.getSeeTimesOneDay();

        YxtSwitch yxtSwitch = yxtSwitchMapper.selectLastOne();
        BigDecimal sum = BigDecimal.ZERO;
        for (Object a:data) {
            AccountEntity entity = (AccountEntity) a;
            //判断是否可以获得奖励
            if (yxtSwitch.getAdvReleaseSwitch() == 1){
                if (!entity.getSeeTimes().equals(seeTimesOneDay)){
                continue;
                }
            }
            try {
                sum = userOrderGainsService.givePointDecCommissionAble(config, allActivationUseCommissionAble, sum, entity);
            }
            catch (Exception e)
            {

            }
        }
        if(allActivationUseCommissionAble.compareTo(BigDecimal.ZERO)==0)
        {
            return ;
        }
//        config.setGiveTotalPoint(MathUtils.setScaleDown(config.getGiveTotalPoint().doubleValue() + sum.doubleValue(),8));
//        pointConfigService.modify(config);

    }

    @Override
    public PageUtils queryBillPage(Map<String, Object> params) {
        IPage<UserBillVo> page = this.baseMapper.queryBillPage(new Query<UserBillVo>().getPage(params),params);
        return new PageUtils(page);
    }

    @Override
    public void monthlyDirectorDividends(Long userId, BigDecimal personalProperty) {

        UserIdentityAssetEntity userIdentityAssetEntity = userIdentityAssetService.getById(userId);
        if (personalProperty.compareTo(userIdentityAssetEntity.getCommissionAble())>0){
            personalProperty = userIdentityAssetEntity.getCommissionAble();
        }
        //修改会员可贡献值
        UserIdentityAssetEntity userIdentity = userIdentityAssetService.updateCommissionAble(userId, personalProperty, false);
        UserBill userBill = new UserBill();
        userBill.setUserId(userId);
        userBill.setBillType(UserBillConstant.BillType.EXPENDITURE);//出账
        userBill.setOuterMode(UserBillConstant.OuterMode.MONTHLY_DIVIDENDS);//出账方式
        userBill.setRemark("董事月度分红");//备注
        userBill.setCode("");//单号
        userBill.setEntryBefore(userIdentity.getCommissionAble().add(personalProperty));//出帐前的可提现佣金
        userBill.setEntryAfter(userIdentity.getCommissionAble());//出帐后的可提现佣金
        userBill.setEntryValue(personalProperty);
        userBill.setOperator("系统");
        this.baseMapper.insert(userBill);

        //修改会员的余额
        saleRefillCardBillService.addBalance(userId,personalProperty,null,BillConstant.InnerMode.MONTHLY_DIVIDENDS);


    }

    @Override
    public void writeOff(Long userId, BigDecimal personalProperty,String orderCode) {
        UserIdentityAssetEntity userIdentityAssetEntity = userIdentityAssetService.getById(userId);
        if (personalProperty.compareTo(userIdentityAssetEntity.getCommissionAble())>0){
            personalProperty = userIdentityAssetEntity.getCommissionAble();
        }
        //修改会员可贡献值
        UserIdentityAssetEntity userIdentity = userIdentityAssetService.updateCommissionAble(userId, personalProperty, false);
        UserBill userBill = new UserBill();
        userBill.setUserId(userId);
        userBill.setBillType(UserBillConstant.BillType.EXPENDITURE);//出账
        userBill.setOuterMode(UserBillConstant.OuterMode.WRITE_OFF);//出账方式
        userBill.setRemark("订单核销");//备注
        userBill.setCode(orderCode);//单号
        userBill.setEntryBefore(userIdentity.getCommissionAble().add(personalProperty));//出帐前的可提现佣金
        userBill.setEntryAfter(userIdentity.getCommissionAble());//出帐后的可提现佣金
        userBill.setEntryValue(personalProperty);
        userBill.setOperator("系统");
        this.baseMapper.insert(userBill);

        //修改会员的余额
        saleRefillCardBillService.addBalance(userId,personalProperty,orderCode,BillConstant.InnerMode.WRITE_OFF);
    }

    @Override
    public void inUserBill(Long userId, String orderCode, BigDecimal consumptionValue, UserBillConstant.BillType income, UserBillConstant.InnerMode buyIncome) {
        //修改会员可贡献值
        UserIdentityAssetEntity userIdentity = userIdentityAssetService.updateCommissionAble(userId,consumptionValue, true);

        UserBill userBill = new UserBill();
        userBill.setUserId(userId);
        userBill.setBillType(income);//入账
        userBill.setInnerMode(buyIncome);//入账方式
        userBill.setRemark("购物");//备注
        userBill.setCode(orderCode);//单号
        userBill.setEntryBefore(userIdentity.getCommissionAble().subtract(consumptionValue));//入帐前的可提现佣金
        userBill.setEntryAfter(userIdentity.getCommissionAble());//入帐后的可提现佣金
        userBill.setEntryValue(consumptionValue);
        userBill.setOperator("系统");
        userBillService.save(userBill);
//        System.out.println("加入mq成功");
//        sendMsgService.sendCommon(MqConstant.UserUpgradeConstant.USER_UPGRADE_EXCHANGE,
//                MqConstant.UserUpgradeConstant.USER_UPGRADE_ROUTER
//                , userId.toString());
    }


}
